#!/usr/bin/env python
# encoding: utf-8
"""
fuckingweather.py - cib 'The Fucking Weather'  Module
Copyright 2012, betrayed/syrius
"""
from urllib import urlopen, urlencode
import lxml.html as lh
import sys
from argparse import ArgumentParser

fuck_url = "http://thefuckingweather.com/?"
indent = "  "

def init(bot):
    global irc
    irc = bot

    irc.cmd.events['PRIVMSG'].subscribe(handle_privmsg)

def handle_privmsg(sender, args):
    msg = args[0].split()
    chan = args[2]

    if msg and msg[0] == '!fw':
        location = ' '.join(msg[1:])

        f_url = fuck_url + urlencode({"where": location})

        try:
            html = urlopen(f_url)
            f_doc = lh.parse(html)
        except:
            irc.privmsg(chan, "Error retrieving Fucking weather data!")
            return

        try:
            fuck = f_doc.xpath("//p/text()")
            fuck2 = f_doc.xpath("//span/text()")
        except:
            irc.privmsg(chan, "Unable to find location!")
            return

        if fuck2:
            irc.privmsg(chan, "Weather for %s" % (fuck2[0]))
            irc.privmsg(chan, "%s%s°" % (indent, fuck2[1]))

            if fuck:
                irc.privmsg(chan, "%s%s (%s)" % (indent, fuck[1], fuck[2]))
            else:
                irc.privmsg(chan, "Weather not found.")
        else:
            irc.privmsg(chan, "Weather not found.")

